package edu.ucdavis.gwt.gis.client.toolbar.button;

import com.google.gwt.dom.client.Style.Overflow;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.VerticalPanel;

import edu.ucdavis.cstars.client.MapWidget;
import edu.ucdavis.gwt.gis.client.extras.CloseButton;
import edu.ucdavis.gwt.gis.client.toolbar.BasemapGallery;
import edu.ucdavis.gwt.gis.client.toolbar.Toolbar;

public class BaseMapButton extends ToolbarItem {
	
	private BasemapGallery gallery = BasemapGallery.INSTANCE;
	private PopupPanel popup = new PopupPanel();
	private VerticalPanel vp = new VerticalPanel();
	private MapWidget map = null;
	private ScrollPanel sp = new ScrollPanel();
	
	public BaseMapButton() {

		
		popup.setStyleName("innerMapPopup");
		popup.setAnimationEnabled(true);
		popup.add(vp);
		
		CloseButton close = new CloseButton();
		close.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				popup.hide();
			}
		});
		HorizontalPanel hp = new HorizontalPanel();
		hp.setWidth("100%");
		hp.getElement().getStyle().setPadding(5, Unit.PX);
		hp.add(new HTML("<div style='font-size:16px;color:#888888;text-align:center'>Select Basemap</div>"));
		hp.add(close);
		hp.setCellHorizontalAlignment(close, HorizontalPanel.ALIGN_RIGHT);
		
		vp.add(hp);
		
		
		vp.setWidth("390px");
		

		sp.add(gallery);
		gallery.getElement().getParentElement().getStyle().setOverflow(Overflow.VISIBLE);
		sp.setSize("390px", "375px");
		sp.getElement().getStyle().setPadding(4, Unit.PX);
		vp.add(sp);
		
	}
	

	public void add(String name, String url, String iconUrl ) {
		if( iconUrl.length() == 0 ) iconUrl = url+"/export?bbox=-20037507.0671618%2C-19971868.8804086%2C20037507.0671618%2C" +
				"19971868.8804086&bboxSR=&layers=&layerdefs=&size=100%2C+67&imageSR=&format=png&transparent=true&dpi=&time=" +
				"&layerTimeOptions=&f=image";
		
		gallery.addBasemap(name, url, iconUrl);
	}
	
	
	public void init(MapWidget mapWidget) {
		map = mapWidget;
	}


	@Override
	public Image getIcon() {
		return null;
	}


	@Override
	public String getText() {
		return "Select Basemap";
	}


	@Override
	public void onAdd(Toolbar toolbar) {}


	@Override
	public void onClick(ClickEvent event) {
		if( popup.isShowing() ) {
			popup.hide();
		} else {
			popup.setPopupPosition(
					map.getAbsoluteLeft()+10,
					map.getAbsoluteTop()+40
			);
			popup.show();
		}
	}

}
